package vip.buddha.service;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.buddha.entity.Account;
import vip.buddha.entity.Orders;
import vip.buddha.entity.Storage;
import vip.buddha.feign.AccountService;
import vip.buddha.feign.StorageService;
import vip.buddha.mapper.OrdersMapper;

@Service
public class OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private StorageService storageService;

    // 需要事务的方法上加入此注解, name自定义保证唯一性
    // A调用B同时A调用C，都只需要在A上加注解
    @GlobalTransactional(name = "save-order", rollbackFor = Exception.class)
    public int save(Orders orders) throws Exception {
        // 1. 扣余额
        Account a = new Account();
        a.setMoney(orders.getMoney());
        Integer i1 = accountService.update(orders.getUserId(), a);
        if (i1 == 0) {
            throw new Exception("扣余额失败");
        }
        // 2. 扣库存
        Storage s = new Storage();
        s.setNum(orders.getNum());
        Integer i2 = storageService.update(orders.getGoodsId(), s);
        if (i2 == 0) {
            throw new Exception("扣库存失败");
        }
        // 3. 添加订单记录
        int i = ordersMapper.insert(orders);
        return i;
    }
}








